﻿using MySql.Data.MySqlClient;

namespace BookManege.service
{
    internal class bookBorrowService
    {
        private MySqlConnection MySqlConnection;
        public bookBorrowService() 
        {
            this.MySqlConnection =  DatabaseUtil.GetMysqlConnection();
        }
        public bool isBorrow(long userId, long bookId)
        {
            string sql = "select id from borrow where user_id = " + userId + " and book_id =" + bookId +" and is_still=0";
            MySqlCommand mySqlCommand =new MySqlCommand(sql, MySqlConnection);
            MySqlDataReader reader = mySqlCommand.ExecuteReader();
            bool isBorrow = reader.Read();
            reader.Close();
            return isBorrow;
        }

        public int borrowBook(long userId,long bookId,int number,DateTime startDate,string endDate)
        {
            string sql1 = "insert into borrow (book_id,number,start_date,end_date,user_id) values (" + bookId + "," + number + ",'" +startDate + "','" + endDate + "'," + userId + ")";
            MySqlCommand mySqlComman1 = new (sql1, MySqlConnection);
            if(DatabaseUtil.MyExecuteNonQuery(sql1) > 0)
            {
                return DatabaseUtil.MyExecuteNonQuery("update book set number = number-" + number + " where id=" + bookId);
            }
            else
            {
                return 0;
            }
        }
    }
}
